package cn.jg.framework.common.model;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.google.common.collect.Maps;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;
import java.util.Map;

/**
 * 基础model兼容类
 */
@Data
@Slf4j
@JsonIgnoreProperties(ignoreUnknown = true, value = {"sqlMap", "page"})
public class SimpleBaseModel implements MixModel<Integer> {
	protected Integer id;
	protected Integer createUserId;
	protected String createUserUsername;
	@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
	protected LocalDateTime createTime;
	protected Integer updateUserId;
	protected String updateUserUsername;
	@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
	protected LocalDateTime updateTime;
	protected String remark;
	protected Integer deleteFlag;
	protected transient Map<String, String> sqlMap;
	// 语言代码（查询参数）
	protected transient String languageCode;
	private transient String page;

	public SimpleBaseModel() {
		super();
		this.deleteFlag = DeleteFlag.NORMAL.getValue();
	}

	public String getCreateUserUsername() {
		if (null != createUserId && 0 == createUserId) {
			return "系统";
		}
		return this.createUserUsername;
	}

	public String getUpdateUserUsername() {
		if (null != updateUserId && 0 == updateUserId) {
			return "系统";
		}
		return this.updateUserUsername;
	}

	public <T extends SimpleBaseModel> T clean() {
		try {
			id = this.getId();
			T t = (T) this.getClass().newInstance();
			t.setId(id);
			return t;
		} catch (InstantiationException | IllegalAccessException e) {
			log.error("clean exception:{}", e);
		}
		return null;
	}

	public void addSqlMap(String key, String value) {
		this.addSqlMap(key, value, 1);
	}

	public void addSqlMap(String key, String value, Integer expectedSize) {
		if (null == sqlMap) {
			sqlMap = Maps.newHashMapWithExpectedSize(expectedSize);
		}
		sqlMap.put(key, value);
	}

	public enum DeleteFlag {
		NORMAL(0), DELETE(1);
		private int value;

		DeleteFlag(int value) {
			this.value = value;
		}

		public int getValue() {
			return value;
		}
	}

}
